require('dotenv').config();
const axios = require('axios');
const cheerio = require('cheerio');
const { wrapper } = require('axios-cookiejar-support');
const { CookieJar } = require('tough-cookie');
const express = require('express');
const app = express();
const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');
const os = require('os');

app.use(express.json());

function updateEnv(req, res) {
    const envPath = path.join(__dirname, '.env');
    const envConfig = dotenv.parse(fs.readFileSync(envPath));

    const newUserAccounts = req.body.USER_ACCOUNT ? req.body.USER_ACCOUNT.split(',') : [];
    const newPasswords = req.body.PASSWORD ? req.body.PASSWORD.split(',') : [];
    const newCaptchas = req.body.CAPTCHA ? req.body.CAPTCHA.split(',') : [];
    const newLoginUrls = req.body.LOGIN_URL;
    const newTargetUrls = req.body.TARGET_URL;

    const existingUserAccounts = envConfig.USER_ACCOUNTS ? envConfig.USER_ACCOUNTS.split(',') : [];
    const existingPasswords = envConfig.PASSWORDS ? envConfig.PASSWORDS.split(',') : [];
    const existingCaptchas = envConfig.CAPTCHAS ? envConfig.CAPTCHAS.split(',') : [];
    const existingLoginUrls = envConfig.LOGIN_URL;
    const existingTargetUrls = envConfig.TARGET_URL;

    const updatedUserAccounts = [...existingUserAccounts];
    const updatedPasswords = [...existingPasswords];
    const updatedCaptchas = [...existingCaptchas];
    let updatedLoginUrls = existingLoginUrls;
    let updatedTargetUrls = existingTargetUrls;

    for (let i = 0; i < newUserAccounts.length; i++) {
        const index = updatedUserAccounts.indexOf(newUserAccounts[i]);
        if (index > -1) {
            // 修改现有用户信息
            if (newPasswords[i]) {
                updatedPasswords[index] = newPasswords[i];
            }
            if (newCaptchas[i]) {
                updatedCaptchas[index] = newCaptchas[i];
            }
        } else {
            // 新增用户信息到最前面
            updatedUserAccounts.unshift(newUserAccounts[i]);
            updatedPasswords.unshift(newPasswords[i] || '');
            updatedCaptchas.unshift(newCaptchas[i] || '');
        }

        if (newLoginUrls !== existingLoginUrls) {
            updatedLoginUrls = newLoginUrls;
        }

        if (newTargetUrls !== existingTargetUrls) {
            updatedTargetUrls = newTargetUrls;
        }
    }

    envConfig.USER_ACCOUNTS = updatedUserAccounts.join(',');
    envConfig.PASSWORDS = updatedPasswords.join(',');
    envConfig.CAPTCHAS = updatedCaptchas.join(',');
    envConfig.LOGIN_URL = updatedLoginUrls;
    envConfig.TARGET_URL = updatedTargetUrls;

    let envData = '';
    for (const [key, value] of Object.entries(envConfig)) {
        envData += `${key}=${value}\n`;
    }

    fs.writeFileSync(envPath, envData);
    require('dotenv').config({ override: true }); // 重新加载.env文件
}

const port = 3000;
const puppeteer = require('puppeteer-core');

// 添加中间件解析表单数据
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static('public'));

app.get('/get_users', (req, res) => {
    const users = process.env.USER_ACCOUNTS.split(',').map((USER_ACCOUNT, index) => ({
        USER_ACCOUNT,
        PASSWORD: process.env.PASSWORDS.split(',')[index] || '',
        CAPTCHA: process.env.CAPTCHAS.split(',')[index] || '',
        LOGIN_URL: process.env.LOGIN_URL,
        TARGET_URL: process.env.TARGET_URL,
    }));

    res.json(users);
});

// 用户选择界面路由
app.get(['/'], (req, res) => {
    res.sendFile(__dirname + '/user_selection.html');
});

// 处理用户配置提交
app.post('/submitConfigure', async (req, res) => {
    updateEnv(req, res);
    // 获取用户选择的环境变量
    const newEnv = { ...process.env, ...req.body };
    if (req.body) {
        res.json({ message: '配置提交成功' });
    }

    console.log('🚀 ~ app.post ~ os.platform():', os.platform());
    try {
        const browser = await puppeteer.launch({
            headless: false,
            executablePath: os.platform() === 'win32' ? process.env.WIN_CHROME_PATH : process.env.MAC_CHROME_PATH,
            args: ['--ignore-certificate-errors', '--ssl-version=any', '--cipher-server-auth='],
            ignoreHTTPSErrors: true,
        });
        const page = await browser.newPage();

        // 导航到登录页面
        await page.goto(newEnv.LOGIN_URL, {
            waitUntil: 'networkidle2',
            ignoreHTTPSErrors: true,
            timeout: 30000,
        });

        await page.waitForSelector('#password', { timeout: 30000 });

        // 输入用户名密码
        await page.type('#username', newEnv.USER_ACCOUNT);
        await page.type('#password', newEnv.PASSWORD);
        await page.type('#captcha', newEnv.CAPTCHA);

        // 等待登录按钮加载
        await page.waitForSelector('#login-btn', { timeout: 30000 });

        // 点击登录按钮
        await Promise.all([
            page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 60000 }),
            page.click('#login-btn'),
        ]);

        // 验证登录状态
        const loginSuccess = await page.evaluate(() => {
            return document.querySelector('body').textContent === 'Login successful!';
        });

        console.log('登录后页面URL:', page.url());
        // const pageContent = await page.content();
        // console.log('页面内容片段:', pageContent.slice(0, 500));

        if (!loginSuccess) {
            throw new Error('登录状态验证失败');
        }
        // 获取登录前的初始cookies
        const initialCookies = await page.cookies();

        // 获取登录后的cookies
        const cookies = await page.cookies();
        const sessionCookie = cookies.map((c) => `${c.name}=${c.value}`).join('; ');

        // 设置全局请求头携带cookie
        await page.setExtraHTTPHeaders({
            Cookie: sessionCookie,
        });

        // 添加网络请求监控
        // await page.setRequestInterception(true);
        // page.on('request', (interceptedRequest) => {
        //     const cookiesHeader = interceptedRequest.headers()['cookie'] || '';
        //     console.log('请求携带Cookies:', cookiesHeader);
        //     interceptedRequest.continue();
        // });

        // 直接使用浏览器访问目标页面
        await page.goto(newEnv.TARGET_URL, {
            waitUntil: 'networkidle2',
            timeout: 30000,
            headers: {
                Cookie: sessionCookie,
            },
        });

        // 验证目标页面加载
        const pageTitle = await page.title();
        console.log('成功访问受保护页面，标题：', pageTitle);

        // 验证页面cookie
        const pageCookies = await page.evaluate(() => document.cookie);
        console.log('页面document.cookie:', pageCookies);
        // if (!pageCookies.includes('sessionid')) {
        //     throw new Error('会话标识未在页面cookie中找到');
        // }

        // 保持浏览器打开供查看
        // await browser.close();
    } catch (error) {
        console.error('发生错误：', error.response?.data || error.message);
    }
});

// 启动服务器
app.listen(port, () => {
    console.log(`配置服务器运行在 http://localhost:${port}`);
});
